package com.groupbuying.admin.controller;

import com.groupbuying.admin.domain.RoleDO;
import com.groupbuying.admin.domain.SysAgentInfoDO;
import com.groupbuying.admin.domain.UserDO;
import com.groupbuying.admin.dto.LoginUserDTO;
import com.groupbuying.admin.dto.UserDTO;
import com.groupbuying.admin.dto.do2dto.UserConvert;
import com.groupbuying.admin.service.RoleService;
import com.groupbuying.admin.service.SysAgentInfoService;
import com.groupbuying.admin.service.UserService;
import com.groupbuying.admin.utils.MD5Utils;
import com.groupbuying.admin.annotation.Log;
import com.groupbuying.admin.context.FilterContextHandler;
import com.groupbuying.admin.utils.PageUtils;
import com.groupbuying.admin.utils.Query;
import com.groupbuying.admin.utils.R;
import com.groupbuying.admin.utils.apiresult.ApiResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 用户信息
 * @author groupbuying
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {
    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    @Autowired
	SysAgentInfoService sysAgentInfoService;

	/**
	 * 登录的当前用户，前台需要验证用户登录的页面可以调用此方法
	 * @return
	 */
    @GetMapping("/currentUser")
	public LoginUserDTO currentUser(){
		LoginUserDTO loginUserDTO = new LoginUserDTO();
		Long roleId = roleService.roleIdsByUserId(Long.parseLong(FilterContextHandler.getUserID())).get(0);

		SysAgentInfoDO sysAgentInfoDO = sysAgentInfoService.get(FilterContextHandler.getAgentId());
		if(sysAgentInfoDO == null || sysAgentInfoDO.getId().equals("00000")){
			//总代理商
			RoleDO roleDO = roleService.get(roleId);
			loginUserDTO.setUserId(FilterContextHandler.getUserID());
			loginUserDTO.setUsername(FilterContextHandler.getUsername());
			//System.out.println(roleDO.getRoleName());
			loginUserDTO.setName("(" + roleDO.getRoleName() + ")" + FilterContextHandler.getName());
			return loginUserDTO;
		} else {
			loginUserDTO.setUserId(FilterContextHandler.getUserID());
			loginUserDTO.setUsername(FilterContextHandler.getUsername());
			loginUserDTO.setName(sysAgentInfoDO.getAgentName());
			return loginUserDTO;
		}
	}

	/**
	 * 根据用户id获取用户
	 * @param id
	 * @return
	 */
    @GetMapping("{id}")
	R get(@PathVariable("id") Long id ){
		UserDTO userDTO = UserConvert.MAPPER.do2dto(userService.get(id));
    	return R.ok().put("data",userDTO);
	}

	/**
	 * 分页查询用户
	 * @param params
	 * @return
	 */
	@Log("获取用户列表")
    @GetMapping()
    public R listByPage(@RequestParam Map<String, Object> params) {
        Query query = new Query(params);
        List<UserDTO> userDTOS = UserConvert.MAPPER.dos2dtos((userService.list(query)));

        for(UserDTO userDTO : userDTOS){
			Long roleId = roleService.roleIdsByUserId(userDTO.getUserId()).get(0);
			RoleDO roleDO = roleService.get(roleId);
			userDTO.setRoleName(roleDO.getRoleName());
		}

		Long roleId = roleService.roleIdsByUserId(Long.parseLong(FilterContextHandler.getUserID())).get(0);
		RoleDO roleDO = roleService.get(roleId);


        int total = userService.count(query);
        PageUtils pageUtil = new PageUtils(userDTOS, total);
        return R.ok().put("page",pageUtil);
    }

	/**
	 * 增加用户
	 * @param user
	 * @return
	 */
	@PostMapping()
    public R save(@RequestBody UserDO user) {
		user.setPassword(MD5Utils.encrypt(user.getUsername(), user.getPassword()));
		return R.operate(userService.save(user) > 0);
	}

	/**
	 * 修改用户
	 * @param user
	 * @return
	 */
	@PutMapping()
	public R update(@RequestBody UserDO user) {
		return R.operate(userService.update(user) > 0);
	}


	/**
	 * 修改用户密码
	 * @return
	 */
	@PostMapping("/changepwd")
	public ApiResult changepwd(@RequestBody Map<String, Object> params) {
		return userService.changeUserPassword(params);
	}

	/**
	 * 删除用户
	 * @param id
	 * @return
	 */
	@DeleteMapping()
	R remove( Long id) {
		return R.operate (userService.remove(id) > 0);
	}

	@PostMapping("/batchRemove")
	@ResponseBody
	R batchRemove(@RequestParam("ids[]") Long[] userIds) {
		int r = userService.batchremove(userIds);
		if (r > 0) {
			return R.ok();
		}
		return R.error();
	}

	@PostMapping("/exits")
	@ResponseBody
	boolean exits(@RequestParam Map<String, Object> params) {
		// 存在，不通过，false
		return !userService.exits(params);
	}

	@RequestMapping("/lists")
	R listsByPage(@RequestParam Map<String, Object> params) {
		System.out.println("------请求列表-------------");
		Query query = new Query(params);
		List<UserDTO> userDTOS = UserConvert.MAPPER.dos2dtos((userService.list(query)));
		int total = userService.count(query);
		PageUtils pageUtil = new PageUtils(userDTOS, total);
		return R.ok().put("page",pageUtil);
	}
}
